package homework;

import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.nio.channels.Pipe;
import java.util.Random;

public class p11911 {
    public static void main(String[] args) throws Exception {
        PipedOutputStream p1=new PipedOutputStream();
        PipedInputStream p2=new PipedInputStream(p1);

        Producer pd1=new Producer(p1);
        Customer cd1=new Customer(p2);
        pd1.start();
        cd1.start();

    }
}

class Producer extends Thread{
    PipedOutputStream pot;
    Random random=new Random();

    Producer(PipedOutputStream pot){
        this.pot=pot;
    }

    public void produce() {

            int i = random.nextInt(200);
            System.out.println("生产了" + i + "产品");
            try {
                pot.write(i);
            } catch (IOException e) {
                e.printStackTrace();
            }
        try {
            sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }


    }

    @Override
    public void run() {
        while (true) {
            produce();
        }
    }
}

class Customer extends Thread{
    PipedInputStream pit;

    Customer(PipedInputStream pit){
        this.pit=pit;
    }

    public void purchase(){
        int i= 0;
        try {
            i = pit.read();
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("购买了"+i+"个产品");

        try {
            sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        while (true) {
            purchase();
        }
    }
}
